package com.crm.log.controller;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.crm.custinfo.domain.CustCommentRecord;
import com.crm.custinfo.domain.CustInfo;
import com.crm.report.domain.CustVisitRecord;
import com.crm.custinfo.service.ICustCommentRecordService;
import com.crm.custinfo.service.ICustInfoService;
import com.crm.report.service.ICustVisitRecordService;
import com.crm.incoming.domain.CustIncomingInfo;
import com.crm.incoming.service.ICustIncomingInfoService;
import com.ruoyi.common.constant.ConfigConstant;
import com.ruoyi.common.constant.StatusConstant;
import com.ruoyi.common.constant.TypeConstant;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysConfigService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.crm.log.domain.UserBusinessLog;
import com.crm.log.service.IUserBusinessLogService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 日志报表Controller
 *
 * @author ruoyi
 * @date 2024-02-12
 */
@RestController
@RequestMapping("/crmsys/businesslog")
public class UserBusinessLogController extends BaseController {
    @Autowired
    private IUserBusinessLogService userBusinessLogService;
    @Autowired
    private ICustInfoService custInfoService;
    @Autowired
    private ISysConfigService baseSysConfigService;
    @Autowired
    private ICustVisitRecordService custVisitRecordService;
    @Autowired
    private ICustIncomingInfoService custIncomingInfoService;
    @Autowired
    private ICustCommentRecordService custCommentRecordService;




    /**
     * 查询日志报表列表
     */
    @PreAuthorize("@ss.hasPermi('crmsys:businesslog:list')")
    @GetMapping("/list")
    public Map<String, Object> list(UserBusinessLog userBusinessLog) {
//        startPage();
//        List<UserBusinessLog> list = userBusinessLogService.selectUserBusinessLogList(userBusinessLog);

        Map<String, Object> resMap = new HashMap<String, Object>();
        Map<String, Object> params = userBusinessLog.getParams();

        String query_type = MapUtils.getString(params, "query_type", "4"); // 默认显示个人业绩排行
        resMap.put("query_type", query_type);

        SysUser user = getLoginUser().getUser();
        SysDept userOrg = getLoginUser().getUser().getDept();
        String right_type = userOrg.getLevel();
        List<SysRole> sysRoles = getLoginUser().getUser().getRoles();

        if (ObjectUtils.equals(TypeConstant.ORG_LEVEL_3, right_type)) {
            // 根据角色代码类别判断是部门经理还是业务员
            right_type = "4";
            for (SysRole sysRole : sysRoles) {
                if (TypeConstant.ROLE_ID_4.equals(sysRole.getRoleKey()) || TypeConstant.ROLE_ID_40.equals(sysRole.getRoleKey())) {
                    right_type = "3";
                    break;
                }
            }
        }
        resMap.put("right_type", right_type); // 1,2,3,4 统计权限级别
        startPage();
        Map<String, Object> result = new HashMap<String, Object>();
        if ("4".equals(query_type)) {
            result = userBusinessLogService.getUserBusinessLogs(0, userBusinessLog);
            result.put("list", getDataTable((List<UserBusinessLog>) result.get("list")));
        } else if ("5".equals(query_type)) {
            try {
                result = userBusinessLogService.getUserBusinessSumLogs(0, userBusinessLog);
                result.put("list", getDataTable((List<Map<String, Object>>) result.get("list")));
            } catch (Exception e) {

            }
        } else {
            result = userBusinessLogService.getOrgBusinessLogs(0, query_type, userBusinessLog);
            result.put("list", getDataTable((List<Map<String, Object>>) result.get("list")));
        }

        return result;
    }


    /**
     * 导出日志报表列表
     */
    @PreAuthorize("@ss.hasPermi('crmsys:businesslog:export')")
    @Log(title = "日志报表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UserBusinessLog userBusinessLog) {
        List<UserBusinessLog> list = userBusinessLogService.selectUserBusinessLogList(userBusinessLog);
        ExcelUtil<UserBusinessLog> util = new ExcelUtil<UserBusinessLog>(UserBusinessLog.class);
        util.exportExcel(response, list, "日志报表数据");
    }

    /**
     * 获取日志报表详细信息
     */
    @PreAuthorize("@ss.hasPermi('crmsys:businesslog:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(userBusinessLogService.selectUserBusinessLogById(id));
    }

    /**
     * 新增日志报表
     */
    @PreAuthorize("@ss.hasPermi('crmsys:businesslog:add')")
    @Log(title = "日志报表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserBusinessLog userBusinessLog) {
        Map<String,Object> errorMap=new HashMap<>();
        List<String> errorList=new ArrayList<>();
        try {
            Date date = new Date();
            SysUser user=getLoginUser().getUser();
            // 待更新状态的客户
            List<CustInfo> custList = new ArrayList<CustInfo>();
            // 待添加备注列表
            List<CustCommentRecord> custComments = new ArrayList<CustCommentRecord>();
            // 进件客户列表
            List<CustIncomingInfo> custIncomings = new ArrayList<CustIncomingInfo>();
            StringBuffer todayVisitCustIds = new StringBuffer();
            StringBuffer todaySignedCustIds = new StringBuffer();
            StringBuffer todayIncomingCustIds = new StringBuffer();
            JSONArray todayvisit =(JSONArray) JSON.parse(userBusinessLog.getTodayVisitContent());
            JSONArray todaysigned =(JSONArray) JSON.parse(userBusinessLog.getTodaySignedContent());
            JSONArray todayincoming =(JSONArray) JSON.parse(userBusinessLog.getTodayIncomingContent());
            //日志日期
            // 今日上门客户
            for (int i = 0; i < todayvisit.size(); i++) {
                JSONObject cust = todayvisit.getJSONObject(i);
                String custId = cust.get("id") == null ? "" : cust.get("id").toString();
                String custDesc = cust.get("custDesc") == null ? "" : cust.get("custDesc").toString();
                CustInfo c = custInfoService.selectCustInfoById(Long.valueOf(custId));
                if (c == null) continue;
                String needCheckVisit = baseSysConfigService.getItemValueByItemKey(ConfigConstant.USER_LOG_NEED_CHECK_VISIT, "0");
                if ("1".equals(needCheckVisit)) {
                    //判断日志当天上门客户是否有扫码记录
                    boolean visited = false;
                    CustVisitRecord visitRecord =new CustVisitRecord();
                    visitRecord.setMobile(c.getMobile());

                    List<CustVisitRecord> visits = custVisitRecordService.selectCustVisitRecordList(visitRecord);
                    if (CollectionUtils.isNotEmpty(visits)) {
                        for (CustVisitRecord visit : visits) {
                            if (visit.getCreateTimeStr() != null && visit.getCreateTimeStr().substring(0, 10).equals(userBusinessLog.getLogDate()) && visit.getEmpMobile().equals(user.getPhonenumber())) {
                                visited = true;
                            }
                        }
                    }
                    if (!visited) {
                        errorList.add(String.format("您所选的上门客户[%s][%s]当日并无扫码记录，请核实扫码后再添加", c.getCustName(), c.getMobile()));
                    }
                }

                CustCommentRecord comment = new CustCommentRecord();
                comment.setCustId(Long.valueOf(custId));
                comment.setEmpId(user.getUserId());
                comment.setEmpName(user.getNickName());
                comment.setRemark(custDesc);
                comment.setCreateTime(date);
                comment.setType(8L);//日志上门备注
                comment.setType2(8L);
                custComments.add(comment);

                if (!StatusConstant.CUST_STATUS_LOAN.equals(c.getStatus()) && !StatusConstant.CUST_STATUS_SIGNED.equals(c.getStatus())) {
                    c.setStatus(StatusConstant.CUST_STATUS_VISIT);//已上门
                }
                c.setLastRemarkTime(new Date());
                c.setUpdateTime(new Date());
                custList.add(c);

                todayVisitCustIds.append(custId);
                if (i != todayvisit.size() - 1) {
                    todayVisitCustIds.append(",");
                }
            }

            // 今日签约客户
            for (int i = 0; i < todaysigned.size(); i++) {
                JSONObject cust = todaysigned.getJSONObject(i);
                String custId = cust.get("id") == null ? "" : cust.get("id").toString();
                String custDesc = cust.get("custDesc") == null ? "" : cust.get("custDesc").toString();
                String related = cust.get("related") == null ? "" : cust.getString("related");
                String relatedcustid = cust.get("relatedcustid") == null ? "" : cust.get("relatedcustid").toString();
                CustInfo c = custInfoService.selectCustInfoById(Long.valueOf(custId));
                if (c == null) continue;

                CustCommentRecord comment = new CustCommentRecord();
                comment.setCustId(Long.valueOf(custId));
                comment.setEmpId(user.getUserId());
                comment.setEmpName(user.getNickName());
                comment.setRemark(custDesc);
                comment.setCreateTime(date);
                comment.setType(1L);//没有固定的备注格式，当做普通备注
                comment.setType2(1L);
                custComments.add(comment);

                comment = new CustCommentRecord();
                comment.setCustId(Long.valueOf(custId));
                comment.setEmpId(user.getUserId());
                comment.setEmpName(user.getNickName());
                comment.setRemark("签约时间");
                comment.setType(3L);//签约备注
                comment.setType2(3L);
                comment.setCreateTime(date);
                custComments.add(comment);

                // 20210805新增校验： 如果当前签约客户是荐介客户，则必须选择是否有关联客户，如果选择是，则必须选择关联客户，并且给该关联客户也生成一条签约备注
                if (TypeConstant.STAR_LEVEL_6.equals(c.getStarLevel())) {
                    if (StringUtils.isBlank(related)) {
                        errorList.add(String.format("请选择签约的荐介客户[%s]是否有关联客户", c.getCustName()));
                    } else if ("1".equals(related)) { // 是否有关联客户选择 "是"
                        if (StringUtils.isBlank(relatedcustid)) {
                            errorList.add(String.format("请选择签约客户[%s]的关联客户", c.getCustName()));
                        } else {
                            CustInfo rc = custInfoService.selectCustInfoById(Long.valueOf(relatedcustid));
                            if (rc != null) {
                                comment = new CustCommentRecord();
                                comment.setCustId(Long.valueOf(relatedcustid));
                                comment.setEmpId(user.getUserId());
                                comment.setEmpName(user.getNickName());
                                comment.setRemark("签约时间");
                                comment.setType(3L);//签约备注
                                comment.setType2(3L);
                                comment.setCreateTime(date);
                                custComments.add(comment);
                            }
                        }
                    }
                }
                if (!StatusConstant.CUST_STATUS_LOAN.equals(c.getStatus())) {
                    c.setStatus(StatusConstant.CUST_STATUS_SIGNED);//已签约
                }
                c.setLastRemarkTime(new Date());
                c.setUpdateTime(new Date());
                custList.add(c);

                todaySignedCustIds.append(custId);
                if (i != todaysigned.size() - 1) {
                    todaySignedCustIds.append(",");
                }
            }

            // 今日进件客户
            for (int i = 0; i < todayincoming.size(); i++) {
                JSONObject cust = todayincoming.getJSONObject(i);
                String custId = cust.get("id") == null ? "" : cust.get("id").toString();
                String incomingBank = cust.get("incomingBank") == null ? "" : cust.get("incomingBank").toString();

                CustInfo c = custInfoService.selectCustInfoById(Long.valueOf(custId));
                if (c == null) continue;
                if (!StatusConstant.CUST_STATUS_LOAN.equals(c.getStatus())) {
                    c.setStatus(StatusConstant.CUST_STATUS_SUBMITED);//审件中
                    custList.add(c);
                }
                CustIncomingInfo custIncomingInfo=new CustIncomingInfo();
                custIncomingInfo.setCustId(c.getId());
                custIncomingInfo.setEmpId(user.getUserId());
                custIncomingInfo.setIncomingDate(userBusinessLog.getLogDate());
                /*p.put("incomingBank", incomingBank);*/
                List<CustIncomingInfo> incomingInfos = custIncomingInfoService.selectCustIncomingInfoList(custIncomingInfo);
                if (CollectionUtils.isEmpty(incomingInfos)) {
                    errorList.add(String.format("客户[%s]今日对应银行进件信息尚未录入,请录入后再行提交", c.getCustName()));
                }
                todayIncomingCustIds.append(custId);
                if (i != todayincoming.size() - 1) {
                    todayIncomingCustIds.append(",");
                }
            }


            userBusinessLog.setTodayVisitCount(Long.valueOf(todayvisit.size()));
            userBusinessLog.setTodayVisitCustids(todayVisitCustIds.toString());
            userBusinessLog.setTodaySignedCount(Long.valueOf(todaysigned.size()));
            userBusinessLog.setTodaySignedCustids(todaySignedCustIds.toString());
            userBusinessLog.setTodayIncomingCount(Long.valueOf(todayincoming.size()));
            userBusinessLog.setTodayIncomingCustids(todayIncomingCustIds.toString());
            userBusinessLog.setEmpId(user.getUserId());
            userBusinessLog.setEmpName(user.getNickName());
            userBusinessLog.setOrgId(user.getDeptId());

            if(!errorList.isEmpty()) {
                //出现异常
                errorMap.put("msg", errorList);
                return AjaxResult.success(errorMap);
            }

            UserBusinessLog userlog = userBusinessLogService.selectUserBusinessLogById(userBusinessLog.getId());
            if (userlog == null) {
                // 如果是新增，则校验当日是否已经添加过日志
                UserBusinessLog businessLog=new UserBusinessLog();
                businessLog.setEmpId(user.getUserId());
                businessLog.setOrgId(user.getDeptId());
                businessLog.setLogDate(userBusinessLog.getLogDate());
                List<UserBusinessLog> exists = userBusinessLogService.selectUserBusinessLogList(businessLog);
                if (CollectionUtils.isNotEmpty(exists)) {
                    errorList.add("当天日志已存在");
                    errorMap.put("msg", errorList);
                    return AjaxResult.success(errorMap);
                }

                userBusinessLog.setCreateTime(date);

                userBusinessLogService.insertUserBusinessLog(userBusinessLog);
            } else {
                userBusinessLog.setUpdateTime(date);
                userBusinessLogService.updateUserBusinessLog(userBusinessLog);
            }

            for (CustInfo custInfo : custList) {
                //更新客户状态
                custInfoService.updateCustInfo(custInfo);
            }
            for (CustCommentRecord custComment : custComments) {
                // 插入客户备注
                custCommentRecordService.insertCustCommentRecord(custComment);
            }


        } catch (Exception e) {
            logger.error("日志添加/更新异常", e);
            errorMap.put("msg", "保存失败");
            return AjaxResult.error("保存失败");
        }
        return AjaxResult.success("保存成功");
    }

    /**
     * 修改日志报表
     */
    @PreAuthorize("@ss.hasPermi('crmsys:businesslog:edit')")
    @Log(title = "日志报表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserBusinessLog userBusinessLog) {
        return toAjax(userBusinessLogService.updateUserBusinessLog(userBusinessLog));
    }

    /**
     * 删除日志报表
     */
    @PreAuthorize("@ss.hasPermi('crmsys:businesslog:remove')")
    @Log(title = "日志报表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(userBusinessLogService.deleteUserBusinessLogByIds(ids));
    }
}
